package com.bwsoft.api.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.api.service.UserService;
import com.bwsoft.api.util.Constant;
import com.bwsoft.util.MD5Util;
import com.bwsoft.util.StringUtils;
import com.bwsoft.util.UploadFileUtil;
import com.bwsoft.util.ValidatorUtil;
@Service(UserService.NAME)
public class UserServiceImpl extends BaseServiceImpl implements UserService{
	private static Logger LOG = Logger.getLogger(UserServiceImpl.class);
	
	/**
	 * 个人用户注册
	 * @param accountType 账户类型
	 * @param phone 手机号
	 * @param code 验证码
	 * @param password 密码
	 */
	@Override
	public ResponsePojo personRegister(Integer accountType, String phone,
			String code, String password) {
		ResponsePojo rp = new ResponsePojo();
		// 判断验证码是否正确
		String verificationCodeHql = "select count(*) from VerificationCode as vc where vc.code=? and vc.number=? and vc.sendTime>=? and vc.status=1 ";
		try {
			Long count = (Long) verificationCodeDao.findByHql(
					verificationCodeHql, code, phone, getBeforDate(-30)).get(0);
			if (count == 0) {
				rp.setErrcode(10);
				rp.setErrmsg("验证码错误！");
				return rp;
			}

			if(hasExist(phone)){
				rp.setErrcode(11);
				rp.setErrmsg("手机号已被注册！");
				return rp;
			}

			Account account = new Account();
			account.setAccountType(accountType);
			account.setPhone(phone);
			account.setAccount(phone);
			account.setPassword(MD5Util.md5_16(password));
			account.setNickName(phone);
			account.setSex(true);
			account.setHeadImgURL(Constant.MOREN_IMG_HEAD);
			account.setAddTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			account.setJinyongFlag(false);
			account.setBirthday(new Date());
			Integer accountId = (Integer) accountDao.save(account);
			account.setAccountId(accountId);
			rp.setErrcode(0);
			rp.setErrmsg("注册成功！");
			rp.setData(accountMap(account));
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e);
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		return rp;
	}
	
	
	/**
	 * 实验室账户注册
	 */
	@Override
	public ResponsePojo libRegister(Integer accountType, String compName,
			Integer compNature, String linkMan, String phone, String address,
			String email, String password, String fax, Boolean cnasFlag,
			File[] img, String[] imgFileName) {
		ResponsePojo rp = new ResponsePojo();
		if(hasExist(email)){
			rp.setErrcode(11);
			rp.setErrmsg("邮箱已被注册！");
			return rp;
		}
		try {
			Account account = new Account();
			account.setAccount(email);
			account.setAccountType(accountType);
			account.setAddress(address);
			account.setCompName(compName);
			account.setCompNature(compNature);
			account.setLinkMan(linkMan);
			account.setPhone(phone);
			account.setEmail(email);
			account.setPassword(MD5Util.md5_16(password));
			account.setNickName(email);
			account.setFax(fax);
			account.setCnasFlag(cnasFlag);
			account.setJinyongFlag(false);
			account.setAttestStatus(0);
			account.setHeadImgURL(Constant.MOREN_IMG_HEAD);
			account.setAddTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")	.format(new Date()));
			String realpath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_SHANGCHUAN);
			String[] fileName=new String[imgFileName.length] ;
			for(int i=0;i<fileName.length;i++){
				if(imgFileName[i]==null||"".equals(imgFileName[i])) continue;
				fileName[i]=UUID.randomUUID().toString()+imgFileName[i].substring(imgFileName[i].lastIndexOf('.'), imgFileName[i].length());
			}
			UploadFileUtil.uploadFile(fileName, img, realpath);
			if(imgFileName[0]!=null&&!"".equals(imgFileName[0])) account.setImg1(Constant.PATH_IMG_SHANGCHUAN+"/"+fileName[0]);
			if(imgFileName[1]!=null&&!"".equals(imgFileName[1])) account.setImg2(Constant.PATH_IMG_SHANGCHUAN+"/"+fileName[1]);
			
			Integer accountId = (Integer) accountDao.save(account);
			account.setAccountId(accountId);
			rp.setErrcode(0);
			rp.setErrmsg("注册成功！");
			rp.setData(accountMap(account));
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e.getStackTrace());
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
	return rp;
	}
	
	
	
	
	
	
	/**
	 * 用户登陆
	 */
	@Override
	public ResponsePojo userLogin(String account, String password) {
		ResponsePojo rp = new ResponsePojo();
		
		try{
			
			String checkUserHql="from Account as ac where ac.account=?";
			
			List<Account> accounts=accountDao.findByHql(checkUserHql, account);
			
			if(accounts.size()==0){
				rp.setErrcode(11);
				rp.setErrmsg("没有此账号！");
				return rp;
			}
			
			Account acc=accounts.get(0);
			
			if(null!=acc.getJinyongFlag()&&acc.getJinyongFlag()){
				rp.setErrcode(11);
				rp.setErrmsg("该账号已经被禁用！");
				return rp;
			}
			
			String pwd=MD5Util.md5_16(password);
			
			if(!acc.getPassword().equals(pwd)){
				rp.setErrcode(10);
				rp.setErrmsg("密码错误！");
				return rp;
			}
			
			acc.setLastLoginTime(new Date());
			accountDao.update(acc);
			
			
			rp.setErrcode(0);
			rp.setErrmsg("登陆成功！");
			rp.setData(accountMap(acc));
			
		}catch (Exception e) {
			LOG.info("异常" + e.getStackTrace());
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
	}
	
	
	/**
	 * 得到用户的详细信息
	 */
	@Override
	public ResponsePojo userInfo(String userid) {
		
ResponsePojo rp = new ResponsePojo();
		
		try{
			
			String checkUserHql="from Account as ac where ac.accountId=?";
			
			List<Account> accounts=accountDao.findByHql(checkUserHql, Integer.parseInt( userid));
			
			LOG.info("共查询到"+accounts.size()+"条用户");
			
			if(accounts.size()==0){
				rp.setErrcode(1);
				rp.setErrmsg("没有此用户信息！");
				return rp;
			}
			
			Account acc=accounts.get(0);
			
			
			rp.setErrcode(0);
			rp.setErrmsg("请求成功！");
			rp.setData(accountInfoMap(acc));
			
		}catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e.toString());
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
	}

	/**
	 * 修改密码
	 */
	@Override
	public ResponsePojo changePwd(String account, String code, String password) {
		ResponsePojo rp = new ResponsePojo();
		
		try{
			
			//查询验证吗
			String checkVerificationCode="select count(*) from VerificationCode as vc where vc.number=? and vc.status=1 and vc.code=? and vc.sendTime>=?";
			
			Long cvcCount=(Long) verificationCodeDao.findByHql(checkVerificationCode, account,code,getBeforDate(-30)).get(0);
			
			if(cvcCount==0){
				
				LOG.info("没找到验证码");
				rp.setErrcode(1);
				rp.setErrmsg("验证码错误！");
				return rp;
				
			}
			
			//查询要修改的用户信息
			String findAccountHql="from Account as ac where ac.account=?";
			
			List<Account> accounts=accountDao.findByHql(findAccountHql, account);
			
			LOG.info("共查询到"+accounts.size()+"条用户");
			
			if(accounts.size()==0){
				rp.setErrcode(1);
				rp.setErrmsg("没有此用户信息！");
				return rp;
			}
			
			Account acc=accounts.get(0);
			
			//设置密码
			acc.setPassword(MD5Util.md5_16(password));
			accountDao.saveOrUpdate(acc);
			
			
			rp.setErrcode(0);
			rp.setErrmsg("密码修改成功！");
			LOG.info("修改密码成功！");
		}catch (Exception e) {
			LOG.info("异常" + e);
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
	}
	
	
	/**
	 *  修改个人信息
	 */
	@SuppressWarnings("unchecked")
	@Override
	public ResponsePojo updatePersonInfo(String userid, String nickname,
			String email, String compName, String address, String birthday,
			String sex) {
		
		ResponsePojo rp = new ResponsePojo();
		
		try{
			
			//查询用户是否存在
			Account account=accountDao.findById(Integer.parseInt(userid));
			
			if(account==null){
				
				LOG.info("没有找到对应的用户编号:"+userid);
				rp.setErrcode(1);
				rp.setErrmsg("没有找到对应的用户编号"+userid);
				return rp;
				
			}
			
			//检查用户名
			String checkNickNameHql="select count(*) from Account as ac where ac.accountId!=? and ac.nickName=?";
			
			Long count=(Long) accountDao.findByHql(checkNickNameHql, Integer.parseInt(userid),nickname).get(0);
			
			if(count>0){
				LOG.info("用户名【"+nickname+"】重复");
				rp.setErrcode(1);
				rp.setErrmsg("用户名【"+nickname+"】重复");
				return rp;
			}
			Account comp=null;
			if(compName!=null&&!compName.trim().equals("")){
			//查询要修改的用户信息
			String checkCompName="from Account as ac where ac.compName=? and ac.accountType in (1,2)";
			
			List<Account> comps=accountDao.findByHql(checkCompName, compName);
			
			LOG.info("共查询到"+comps.size()+"个公司");
			
			if(comps.size()==0){
				rp.setErrcode(1);
				rp.setErrmsg("没有找到名为【"+compName+"】的公司");
				return rp;
			}
			
			comp=comps.get(0);			//对应单位
			}
			if(account.getAccountType()!=3&&account.getAccountType()!=4){
				LOG.info("该方法只为个人类型用户修改信息");
				rp.setErrcode(1);
				rp.setErrmsg("该方法只为个人类型用户修改信息");
				return rp;
			}
			
			
			account.setNickName(nickname);
			account.setAddress(address);
			account.setEmail(email);
			account.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
			account.setSex(sex.equals("1"));
			account.setCompany(comp);
			account=accountDao.getHibernateTemplate().merge(account);
			accountDao.update(account);
			
			rp.setErrcode(0);
			rp.setErrmsg("修改成功！");
			rp.setData(accountInfoMap(account));
		}catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e);
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
		
	}

	
/**
 * 更新企业用户信息
 */
	@Override
	public ResponsePojo updateLibInfo(String userid, String nickname,
			String linkMan, String phone, String address, String fax) {
		
		ResponsePojo rp = new ResponsePojo();
		
		try{
			
			//查询用户是否存在
			Account account=accountDao.findById(Integer.parseInt(userid));
			
			if(account==null){
				
				LOG.info("没有找到对应的用户编号:"+userid);
				rp.setErrcode(1);
				rp.setErrmsg("没有找到对应的用户编号"+userid);
				return rp;
				
			}
			
			//检查用户名
			String checkNickNameHql="select count(*) from Account as ac where ac.accountId!=? and ac.nickName=?";
			
			Long count=(Long) accountDao.findByHql(checkNickNameHql, Integer.parseInt(userid),nickname).get(0);
			
			if(count>0){
				LOG.info("用户名【"+nickname+"】重复");
				rp.setErrcode(1);
				rp.setErrmsg("用户名【"+nickname+"】重复");
				return rp;
			}
			
			
			if(account.getAccountType()!=1&&account.getAccountType()!=2){
				LOG.info("该方法只为机构类型用户修改信息");
				rp.setErrcode(1);
				rp.setErrmsg("该方法只为机构类型用户修改信息");
				return rp;
			}
			
			
			account.setNickName(nickname);
			account.setAddress(address);
			account.setLinkMan(linkMan);
			account.setFax(fax);
			account.setPhone(phone);
			account=accountDao.getHibernateTemplate().merge(account);
			accountDao.update(account);
			
			rp.setErrcode(0);
			rp.setErrmsg("修改成功！");
			rp.setData(accountInfoMap(account));
		}catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e);
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
	}
	
	
	/**
	 * 得到几分钟之后的 DATE类型数据
	 * @param addMinute 几分钟之后
	 * @return
	 */
	public Date getBeforDate(int addMinute){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, addMinute);
		return calendar.getTime();
	}
	
	public Map<String,Object> accountMap(Account account){
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("accountType",account.getAccountType());
			map.put("accountTypeName", dictionaryDataService.getDicValueDataByNameValue("account_type", account.getAccountType()));
			map.put("userId", account.getAccountId());
			map.put("nickName", account.getNickName());
			map.put("attestStatus",account.getAttestStatus());
			map.put("attestStatusName",dictionaryDataService.getDicValueDataByNameValue("attest_Status",  account.getAttestStatus()));
			map.put("headImgURL", account.getHeadImgURL());
			map.put("aboutUs", Constant.URL_ABOUTUS);
		return map;
	}
	
	/**
	 * 得到用户详细信息
	 * @param account
	 * @return
	 */
	public Map<String,Object> accountInfoMap(Account account){
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("id", account.getAccountId());
		map.put("account", account.getAccount());
		map.put("nickName", account.getNickName());
		map.put("accountType",account.getAccountType());
		map.put("accountTypeName",  dictionaryDataService.getDicValueDataByNameValue("account_type", account.getAccountType()));
		map.put("headImgURL", account.getHeadImgURL());
		map.put("phone", account.getPhone());
		map.put("email", account.getEmail());
		map.put("personCompName", account.getCompany()==null?"":  account.getCompany().getCompName());
		map.put("address", account.getAddress());
		map.put("birthday", account.getBirthday()==null?"":new SimpleDateFormat("yyyy-MM-dd").format(account.getBirthday()));
		map.put("sex", account.getSex()?"男":"女");
		map.put("compName", account.getCompany()!=null?account.getCompany().getCompName():"");
		map.put("compNature", dictionaryDataService.getDicValueDataByNameValue("comp_nature", account.getCompNature()));
		map.put("linkman", account.getLinkMan());
		map.put("fax", account.getFax());
		map.put("attestStatus",account.getAttestStatus());
		map.put("attestStatusName",dictionaryDataService.getDicValueDataByNameValue("attest_Status",  account.getAttestStatus()));
	return map;
}
	
	
	/**
	 * 判断账户是否已经存在
	 * @param account
	 * @return
	 */
	public Boolean hasExist(String account){
		String hasExistHql = "select count(*) from Account as a where a.account=?";
		Long count = (Long) verificationCodeDao.findByHql(
				hasExistHql,account).get(0);
		return count>0;
	}


	/**
	 * 	判断是否为图片类型
	 */
	@Override
	public boolean isImage(String[] imgContentType) {
		Boolean flag=true;
		for (String string : imgContentType) {
			if(!ValidatorUtil.isImage(string.toLowerCase())){
				flag=false;
				break;
			}
		}
		return flag;
	}

	
	/**
	 *  判断图片的大小是否超过了预期值
	 */
	@Override
	public boolean isFitSize(File[] img) {
		boolean flag=true;
		for (File file : img) {
			if(file.length()>Constant.SIZE_UPLOAD_IMG){
				flag=false;
				break;
			}
		}
		return flag;
	}


	/**
	 * 修改头像头像
	 */
	@Override
	public ResponsePojo updateHeadImage(String userid, File[] img,
			String[] imgFileName) {
ResponsePojo rp = new ResponsePojo();
		
		try{
			
			//查询用户是否存在
			Account account=accountDao.findById(Integer.parseInt(userid));
			
			if(account==null){
				
				LOG.info("没有找到对应的用户编号:"+userid);
				rp.setErrcode(1);
				rp.setErrmsg("没有找到对应的用户编号"+userid);
				return rp;
				
			}
			Calendar now = Calendar.getInstance(); 
			String realpath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_HEADIMG+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
			String[] fileName=new String[imgFileName.length] ;
			for(int i=0;i<fileName.length;i++){
				fileName[i]=UUID.randomUUID().toString()+imgFileName[i].substring(imgFileName[i].lastIndexOf('.'), imgFileName[i].length());
			}
			UploadFileUtil.uploadFile(fileName, img, realpath);
			account.setHeadImgURL(Constant.PATH_IMG_HEADIMG+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+fileName[0]);
			account=accountDao.getHibernateTemplate().merge(account);
			accountDao.update(account);
			
			rp.setErrcode(0);
			rp.setErrmsg("修改成功！");
			rp.setData(accountInfoMap(account));
		}catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e);
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
	}


	@Override
	public ResponsePojo returnLoginMsg(String userid, String phoneOS,
			String phoneModel, String registrationID) {
			ResponsePojo rp = new ResponsePojo();
		
		try{
			
			
			Account acc=accountDao.findById(Integer.parseInt( userid));
			
			if(acc==null){
				rp.setErrcode(11);
				rp.setErrmsg("没有此账号！");
				return rp;
			}
			
			acc.setPhoneModel(phoneModel);
			acc.setPhoneOS(phoneOS);
			acc.setRegistrationID(registrationID);
			acc.setLastLoginTime(new Date());
			
			
			accountDao.update(acc);
			
			rp.setErrcode(0);
			rp.setErrmsg("操作成功成功！");
			
		}catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e.getStackTrace());
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
	}






	










	
}
